/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.ChangePasswordRequestMessage;
import cn.easyplatform.messages.vos.LoginVo;
import cn.easyplatform.messages.vos.UserPasswordVo;
import cn.easyplatform.spi.service.IdentityService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.UserType;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Button;
import org.zkoss.zul.Captcha;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ChangePasswordController extends SelectorComposer<Window> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;


    @Wire("textbox#oldPass")
    private Textbox oldPass;

    @Wire("textbox#newPass")
    private Textbox newPass;

    @Wire("textbox#newPassConfirm")
    private Textbox newPassConfirm;

    @Wire("textbox#captchabox")
    private Textbox captchabox;

    @Wire("captcha#captcha")
    private Captcha captcha;

    @Wire("button#submit")
    private Button submit;

    public void doAfterCompose(Window win) throws Exception {
        super.doAfterCompose(win);
        oldPass.setWidgetListener(Events.ON_OK,
                "if(this.getValue()!=''){web.Widget.$('" + newPass.getUuid()
                        + "').focus();}");
        newPass.setWidgetListener(
                Events.ON_OK,
                "if(this.getValue().length>5)web.Widget.$('"
                        + newPassConfirm.getUuid() + "').focus()");
        newPassConfirm.setWidgetListener(Events.ON_OK,
                "if(this.getValue().length>5)web.Widget.$('" + captchabox.getUuid()
                        + "').focus()");
        captchabox.setWidgetListener(
                Events.ON_OK,
                "if(this.getValue().length==5){var wgt = web.Widget.$('"
                        + submit.getUuid()
                        + "');wgt.focus();wgt.fire('onClick');}");
        win.doHighlighted();
    }

    @Listen("onClick=#submit")
    public void submit() {
        if (Strings.isBlank(oldPass.getValue())) {
            oldPass.setErrorMessage(Labels
                    .getLabel("user.old.password.placeholder"));
            oldPass.setFocus(true);
            return;
        }
        if (Strings.isBlank(newPass.getValue())) {
            newPass.setErrorMessage(Labels
                    .getLabel("user.new.password.placeholder"));
            newPass.setFocus(true);
            return;
        }
        if (newPass.getValue().trim().length() < 6) {
            newPass.setErrorMessage(Labels.getLabel("user.password.length"));
            newPass.setFocus(true);
            return;
        }
        if (!chackComplex(newPass.getValue().trim())) {
            newPass.setErrorMessage(Labels.getLabel("user.password.complex"));
            newPass.setFocus(true);
            return;
        }
        if (Strings.isBlank(newPassConfirm.getValue())) {
            newPassConfirm.setErrorMessage(Labels
                    .getLabel("user.new.password.confirm.placeholder"));
            newPassConfirm.setFocus(true);
            return;
        }
        if (!newPass.getValue().equals(newPassConfirm.getValue())) {
            newPassConfirm.setErrorMessage(Labels
                    .getLabel("user.new.password.match"));
            newPassConfirm.setFocus(true);
            return;
        }
        if (Strings.isBlank(captchabox.getValue())) {
            captchabox.setErrorMessage(Labels
                    .getLabel("user.captcha.placeholder"));
            captchabox.setFocus(true);
            return;
        }
        if (!captchabox.getValue().toLowerCase()
                .equals(captcha.getValue().toLowerCase())) {
            captchabox.setErrorMessage(Labels.getLabel("user.captcha.match"));
            captchabox.setFocus(true);
            return;
        }
        IResponseMessage<?> resp = null;
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        LoginVo loginVo = Contexts.getUser();
        if (loginVo.getType() == UserType.TYPE_SUPER) {//超级用户
            if (!loginVo.getPassword().equals(oldPass.getValue())) {
                Clients.wrongValue(submit, Labels.getLabel("user.password.invalid"));
                return;
            } else {
                resp = uc
                        .changePassword(new ChangePasswordRequestMessage(
                                new UserPasswordVo(loginVo.getId(), newPass
                                        .getValue())));
            }
        } else {
            resp = uc
                    .changePassword(new ChangePasswordRequestMessage(
                            new UserPasswordVo(oldPass.getValue(), newPass
                                    .getValue())));
        }
        if (resp.isSuccess()) {
            Component c = submit.getPage().getFellowIfAny("gv5user");
            if (c != null)
                Clients.showNotification(Labels.getLabel("user.password.success"),
                        "info", c,
                        "start_before", -1, true);
            loginVo.setPassword(newPass.getValue());
            submit.getRoot().detach();
        } else if (resp.getCode().equals("E066")) {
            oldPass.setErrorMessage((String) resp.getBody());
            oldPass.setFocus(true);
        } else
            Clients.wrongValue(submit, (String) resp.getBody());

    }


    public boolean chackComplex(String password){
        String regex = "^(?=.*[A-Za-z])(?=.*[a-z])(?![0-9]+$)(?![^0-9]+$)(?![a-zA-Z]+$)(?![^a-zA-Z]+$)(?![a-zA-Z0-9]+$)[a-zA-Z0-9\\S]{8,16}$";
        return password.matches(regex);
    }
}
